﻿using AiBLSmartEdu.Module.SmartEnglish.API.Configurations;
using AiBLSmartEdu.Module.SmartEnglish.API.DTOs;
using AutoMapper;
using Domain;
using Domain.Entities;
using FrameworkCore.DI;
using FrameworkCore.Extensions;
using FrameworkCore.Helpers;
using FrameworkCore.Models;
using FrameworkCore.Repositories;
using Microsoft.Extensions.Options;

namespace AiBLSmartEdu.Module.SmartEnglish.API.Services;

#nullable disable

/// <summary>
/// 智慧英语服务
/// </summary>
public class SmartEnglishServices : IScopedDependency
{
    private readonly IRepository<Vocabulary> _vocabularyRepository;
    private readonly IOptions<SmartEnglishSecretSettings> _optSmartEnglishSecretSettings;
    private readonly IMapper _mapper;

    public SmartEnglishServices(
       IRepository<Vocabulary> vocabularyRepository,
       IMapper mapper,
       IOptions<SmartEnglishSecretSettings> optSmartEnglishSecretSettings)
    {
        _vocabularyRepository = vocabularyRepository;
        _mapper = mapper;
        _optSmartEnglishSecretSettings = optSmartEnglishSecretSettings;
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="filter">分页输入模型</param>
    /// <returns></returns>
    public async Task<PageResult<VocabularyOutputModel>> PageAsync(VocabularyPaginationFilter filter)
    {
        return (await _vocabularyRepository.GetOrderedQueryable(query =>
        {
            return query.WhereIf(!filter.Word.IsNullOrWhiteSpace(), x => x.Word.Contains(filter.Word))
                        .WhereIf(filter.IsFavorited.HasValue, x => x.IsFavorited == filter.IsFavorited)
                        .WhereIf(filter.LearningStatus.HasValue, x => x.LearningStatus == filter.LearningStatus);

        }, filter).ProjectToPaginatedDataAsync<Vocabulary, VocabularyOutputModel>(
            filter.PageNumber,
            filter.PageSize,
            _mapper.ConfigurationProvider
        )).ToPageList();
    }

    /// <summary>
    /// 创建词汇
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task CreateAsync(VocabularyCreateInputModel input)
    {
        var isExist = _vocabularyRepository.Query(x => x.Word == input.Word).Any();
        ExceptionHelper.ThrowIfTrue(isExist, "词汇已存在");

        var model = _mapper.Map<Vocabulary>(input);
        model.Description = await FetchWordDataAsync(input.Word);
        model.LearningStatus = LearningStatus.NotStarted;
        await _vocabularyRepository.InsertAsync(model);
    }

    /// <summary>
    /// 修改状态
    /// </summary>
    /// <param name="id">唯一标识</param>
    /// <param name="status">状态</param>
    /// <returns></returns>
    public async Task UpdateStatusAsync(long id, LearningStatus status)
    {
        await _vocabularyRepository.UpdateAsync(x => x
        .SetProperty(p => p.LearningStatus, p => status), w => w.Id == id);
    }

    /// <summary>
    /// 是否收藏
    /// </summary>
    /// <param name="id">唯一标识</param>
    /// <returns></returns>
    public async Task IsFavoritedAsync(long id)
    {
        await _vocabularyRepository.UpdateAsync(x => x.SetProperty(p => p.IsFavorited, p => !p.IsFavorited), w => w.Id == id);
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="ids">唯一标识，多个使用英文状态下的逗号（,）隔开</param>
    /// <returns></returns>
    public async Task DeleteAsync(string ids)
    {
        ExceptionHelper.ThrowIfNull(ids, "删除的唯一标识不能为空");

        List<long> idsToDelste = ids
            .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)  // 分割字符串
            .Select(id =>
            {
                if (long.TryParse(id.Trim(), out long result))
                {
                    return result;
                }
                else
                {
                    ExceptionHelper.ThrowIfTrue(true, "无效的标识");
                    return 0;
                }
            }).ToList();

        await _vocabularyRepository.DeleteAsync(x => idsToDelste.Contains(x.Id));
    }


    private async Task<string> FetchWordDataAsync(string word)
    {
        string url = string.Format(_optSmartEnglishSecretSettings.Value.Url,word);

        using (HttpClient client = new HttpClient())
        {
            // 模仿浏览器请求的头
            client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
            client.DefaultRequestHeaders.Add("Accept", "application/json");

            try
            {
                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();

                return await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException e)
            {
                return e.Message; 
            }
        }
    }
}
